//
//  NSTableKeyActions.m
//  Secret Santa
//
//  Created by Andrew Cain on 19/10/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "NSTableKeyActions.h"

@implementation NSTableView ( DeleteKey )

- ( void ) keyDown: ( NSEvent * ) event 
{
	id obj = [self delegate];
	unichar firstChar = [[event characters] characterAtIndex: 0];
	
	// if the user pressed delete and the delegate supports deleteKeyPressed
	if ( ( firstChar == NSDeleteFunctionKey ||
		   firstChar == NSDeleteCharFunctionKey ||
		   firstChar == NSDeleteCharacter) &&
		 [obj respondsToSelector: @selector( deleteKeyPressed:onRow: )] ) 
	{
		id < DeleteKeyDelegate > delegate = ( id < DeleteKeyDelegate > ) obj;
		
		[delegate deleteKeyPressed: self onRow: [self selectedRow]];
	}
	else
	{
		[self interpretKeyEvents:[NSArray arrayWithObject:event]];
	}
}


- (void)moveDown:(id)sender {
	[self scrollLineDown:sender];
}

- (void)moveUp:(id)sender {
	[self scrollLineUp:sender];
}

- (void)scrollToRow:(int)row selectRow:(BOOL)select {
	if (select) [self selectRow:row byExtendingSelection:NO];
	[self scrollRowToVisible:row];
}

- (void)scrollLineUp:(id)sender {
	int row = [self selectedRow];
	if (row < 0) row = [self numberOfRows];
	if (--row >= 0) [self scrollToRow:row selectRow:YES];
}

- (void)scrollLineDown:(id)sender {
	int row = [self selectedRow];
	if (++row < [self numberOfRows]) [self scrollToRow:row selectRow:YES];
}

- (void)scrollToBeginningOfDocument:(id)sender {
	int rows = [self numberOfRows];
	if (rows) [self scrollToRow:rows selectRow:NO];
}

- (void)scrollToEndOfDocument:(id)sender {
	int rows = [self numberOfRows];
	if (rows) [self scrollToRow:rows-1 selectRow:NO];
}

- (void)cancel:(id)sender {
	[self abortEditing];
	[[self window] makeFirstResponder:self];
}

- (void)moveRight:(id)sender {
	id row;
	NSEnumerator *enumerator = [self selectedRowEnumerator];
	
	while (row = [enumerator nextObject]) {
		[self expandItem:[self itemAtRow:[row intValue]]];
	}
}

- (void)moveLeft:(id)sender {
	id row;
	NSEnumerator *enumerator = [self selectedRowEnumerator];
	
	while (row = [enumerator nextObject]) {
		[self collapseItem:[self itemAtRow:[row intValue]]];
	}
}
@end
